package com.two.screen.water.balance.utils.voice;


import static com.two.screen.water.balance.utils.voice.constant.VoiceConstants.SUCCESS_OTHER_PAY;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

import com.two.screen.water.balance.utils.voice.constant.VoiceConstants;
import com.two.screen.water.balance.utils.voice.util.FileUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VoicePlay {

    private ExecutorService mExecutorService;
    private Context mContext;

    private VoicePlay(Context context) {
        this.mContext = context;
        this.mExecutorService = Executors.newCachedThreadPool();
    }

    private volatile static VoicePlay mVoicePlay = null;

    /**
     * 单例
     *
     * @return
     */
    public static VoicePlay with(Context context) {
        if (mVoicePlay == null) {
            synchronized (VoicePlay.class) {
                if (mVoicePlay == null) {
                    mVoicePlay = new VoicePlay(context);
                }
            }
        }
        return mVoicePlay;
    }

    /**
     * 默认收款成功样式
     *
     * @param money
     */
    /*public void play(String money) {
        play(money, false);
    }*/

    /**
     * 设置播报数字
     *
     * @param money
     */
    public void play(String money, String start) {
        VoiceBuilder voiceBuilder = new VoiceBuilder.Builder()
                .start(start)
                .money(money)
                .unit(VoiceConstants.YUAN)
                .checkNum(false)
                .builder();
        executeStart(voiceBuilder);
    }
    /**
     * 设置播报数字
     *
     * @param money
     */
    public void testPlay() {
        VoiceBuilder voiceBuilder = new VoiceBuilder.Builder()
                .start(SUCCESS_OTHER_PAY)
                .money("123456780.9")
                .unit(VoiceConstants.YUAN)
                .checkNum(true)
                .builder();
        executeStart(voiceBuilder);
    }

    /**
     * 接收自定义
     *
     * @param start
     */
    public void play(String start, Boolean isContinuePlay) {
        VoiceBuilder voiceBuilder = new VoiceBuilder.Builder()
                .start(start)
                .isContinuePlay(isContinuePlay)
                .builder();
        executeStart(voiceBuilder);
    }

    /**
     * 开启线程
     *
     * @param builder
     */
    private void executeStart(VoiceBuilder builder) {
        List<String> voicePlay = VoiceTextTemplate.genVoiceList(builder);
        if (voicePlay == null || voicePlay.isEmpty()) {
            return;
        }

        mExecutorService.execute(() -> {
            try {
                start(voicePlay, builder.isContinuePlay());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 开始播报
     *
     * @param voicePlay
     * @param continuePlay
     */
    MediaPlayer mMp = new MediaPlayer();

    private void start(final List<String> voicePlay, boolean continuePlay) {
        if (continuePlay) {
            synchronized (VoicePlay.this) {
                MediaPlayer mMediaPlayer = new MediaPlayer();
                final CountDownLatch mCountDownLatch = new CountDownLatch(1);
                AssetFileDescriptor assetFileDescription = null;

                try {
                    final int[] counter = {0};
                    assetFileDescription = FileUtils.getAssetFileDescription(mContext,
                            String.format(VoiceConstants.FILE_PATH, voicePlay.get(counter[0])));
                    mMediaPlayer.setDataSource(
                            assetFileDescription.getFileDescriptor(),
                            assetFileDescription.getStartOffset(),
                            assetFileDescription.getLength());
                    mMediaPlayer.prepareAsync();
                    mMediaPlayer.setOnPreparedListener(mediaPlayer -> mMediaPlayer.start());
                    mMediaPlayer.setOnCompletionListener(mediaPlayer -> {
                        mediaPlayer.reset();
                        counter[0]++;

                        if (counter[0] < voicePlay.size()) {
                            try {
                                AssetFileDescriptor fileDescription2 = FileUtils.getAssetFileDescription(mContext,
                                        String.format(VoiceConstants.FILE_PATH, voicePlay.get(counter[0])));
                                mediaPlayer.setDataSource(
                                        fileDescription2.getFileDescriptor(),
                                        fileDescription2.getStartOffset(),
                                        fileDescription2.getLength());
                                mediaPlayer.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                                mCountDownLatch.countDown();
                            }
                        } else {
                            mediaPlayer.release();
                            mCountDownLatch.countDown();
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                    mCountDownLatch.countDown();
                } finally {
                    if (assetFileDescription != null) {
                        try {
                            assetFileDescription.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                try {
                    mCountDownLatch.await();
                    notifyAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (mMp != null) {
                try {
                    mMp.stop();
                    mMp.release();
                    mMp = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mMp = new MediaPlayer();
            final CountDownLatch mCountDownLatch = new CountDownLatch(1);
            AssetFileDescriptor assetFileDescription = null;

            try {
                final int[] counter = {0};
                assetFileDescription = FileUtils.getAssetFileDescription(mContext,
                        String.format(VoiceConstants.FILE_PATH, voicePlay.get(counter[0])));
                mMp.setDataSource(
                        assetFileDescription.getFileDescriptor(),
                        assetFileDescription.getStartOffset(),
                        assetFileDescription.getLength());
                mMp.prepareAsync();
                mMp.setOnPreparedListener(mediaPlayer -> mMp.start());
                mMp.setOnCompletionListener(mediaPlayer -> {
                    mediaPlayer.reset();
                    counter[0]++;

                    if (counter[0] < voicePlay.size()) {
                        try {
                            AssetFileDescriptor fileDescription2 = FileUtils.getAssetFileDescription(mContext,
                                    String.format(VoiceConstants.FILE_PATH, voicePlay.get(counter[0])));
                            mediaPlayer.setDataSource(
                                    fileDescription2.getFileDescriptor(),
                                    fileDescription2.getStartOffset(),
                                    fileDescription2.getLength());
                            mediaPlayer.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                            mCountDownLatch.countDown();
                        }
                    } else {
                        mediaPlayer.release();
                        mCountDownLatch.countDown();
                    }
                });


            } catch (Exception e) {
                e.printStackTrace();
                mCountDownLatch.countDown();
            } finally {
                if (assetFileDescription != null) {
                    try {
                        assetFileDescription.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            try {
                mCountDownLatch.await();
//                notifyAll();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
